<?php
/**
 * Prado Portal.
 *
 * @author Steen Rabol <steen.rabol@gmail.com>
 * @link http://www.pradoportal.dk/
 * @copyright Copyright &copy; 2006,2007,2008 Steen Rabol
 * @license http://www.pradoportal.dk
 * @version $Id: SiteMenuEdit.php 468 2011-01-25 17:25:12Z steen.rabol $
 *
 */

Prado::using('Application.Common.Data.PortalSiteMenuRecord');
Prado::using('Application.Common.Data.PortalSiteMenuItemRecord');
Prado::using('Application.Common.Data.PortalRoleRecord');
Prado::using('Application.Common.Data.PortalPageRecord');
Prado::using('Application.Common.Web.UI.WebControls.TJSCookTree.TJSCookTree');

class SiteMenuEdit extends PortalAdminPage
{
	private	$_sitemenurecord	= null;
	private	$_parent			= 0;

	public function getDataRows($offset, $rows)
	{
		$criteria = new TActiveRecordCriteria;
		$criteria->Condition				= 'smid = :smid and parent=:parent';
		$criteria->Parameters[':smid']		= $this->SiteMenuRecord->id;
		$criteria->Parameters[':parent']	= $this->_parent;
		$criteria->OrdersBy['displayorder']	= 'asc';
		$criteria->Limit					= $rows;
		$criteria->Offset					= $offset;

		return PortalSiteMenuItemRecord::finder()->findAll($criteria);
	}

	protected function getRowCount()
    {
    	$smid	= $this->SiteMenuRecord->id;
    	$parent	= $this->_parent;

        return $this->DataAccess->createCommand("select count(id) from tblsitemenuitem where smid=$smid and parent=$parent")->queryScalar();
    }

	public function pageChanged($sender,$param)
    {
        $this->dlSiteMenuItemsList->CurrentPageIndex	= $param->NewPageIndex;
		$this->dlSiteMenuItemsList->DataSource	= $this->getDataRows(0,$this->dlSiteMenuItemsList->PageSize * $this->dlSiteMenuItemsList->CurrentPageIndex);
		$this->dlSiteMenuItemsList->dataBind();
    }

	public function setMenuParent($value)
	{
		$this->_parent	= $value;
	}

	public function getMenuParent()
	{
		return $this->_parent;
	}

	public function onInit($param)
	{
		parent::onInit($param);

		if(isset($this->Request['parent']))
		{
			$this->MenuParent	= TPropertyValue::ensureInteger($this->Request['parent']);

	    	$mi = PortalSiteMenuItemRecord::finder()->findByid($this->MenuParent);
	    	$p = $mi !== null ? $mi->parent : 0;

			$this->GoUp->NavigateUrl = $this->Service->constructUrl('Admin.SiteMenuEdit',array("id" => $this->Request['id'],"parent"=>$p));
		}
	}

	public function onLoad($param)
	{
		parent::onLoad($param);
		$this->setAdminPageTitle("Edit sitemenu");

		if(!$this->IsPostBack)
		{
			$this->PagePath->DataSource	= $this->DataAccess->createCommand("select * from tblpagepath")->query();
			$this->PagePath->dataBind();

			foreach(PortalUtil::getAvailablePortalLayouts() as $l)
			{
				$pl[] = array("name" => $l['name'], "id" => $l['id']);
			}

			$this->PageLayout->DataSource 		= $pl;
			$this->PageLayout->DataBind();

			$this->Role->DataSource	= $this->getRoles();
			$this->Role->dataBind();

			$this->ddlPage->DataSource	= $this->getPages();
			$this->ddlPage->dataBind();

			$this->dlSiteMenuItemsList->VirtualItemCount	= $this->RowCount;
			$this->dlSiteMenuItemsList->DataSource			= $this->getDataRows(0,$this->dlSiteMenuItemsList->PageSize);
			$this->dlSiteMenuItemsList->dataBind();
		}
	}

	public function getSiteMenuRecord()
	{
		if($this->_sitemenurecord === null)
		{
			$this->_sitemenurecord = PortalSiteMenuRecord::finder()->findByid($this->Request['id']);
		}

		return $this->_sitemenurecord;
	}

	public function SaveSiteMenuItem($sender, $param)
	{
		if($this->IsValid)
		{
			$smi					= new PortalSiteMenuItemRecord();
			$smi->smid				= $this->SiteMenuRecord->id;
			$smi->title				= $this->tbTitle->Text;
			$smi->page				= $this->ddlPage->SelectedValue;
			$smi->img				=  '';
			$smi->active			= TPropertyValue::ensureInteger($this->Active->Checked);
			$smi->role				= TPropertyValue::ensureInteger($this->Role->SelectedValue);
			$smi->parent			= $this->MenuParent;
			$smi->target			= $this->ddlTarget->SelectedValue;
			$smi->isbreak			= TPropertyValue::ensureInteger($this->cbSeparator->Checked);
			$smi->displayorder		= 999;
			$smi->needlogin			= TPropertyValue::ensureInteger($this->cbNeedLogin->Checked);
			$smi->showafterlogin	= TPropertyValue::ensureInteger($this->cbShowAfterLogin->Checked);
			$smi->save();
			$this->RenumDisplayOrder(1);
			//Build our urlmap file
			$this->Application->BuildUrlMappingsForPath(true);

			if($this->tcbCreateNewPage->Checked)
			{
				$this->CreateNewPage($smi);
			}

			$this->gotoPage('Admin.SiteMenuEdit',array("id" => $this->Request['id'],"parent"=> $this->MenuParent));
		}
	}

	public function updateItem($sender,$param)
	{
		$item=$param->Item;
		$id = $this->dlSiteMenuItemsList->DataKeys[$item->ItemIndex];

		$smi					= PortalSiteMenuItemRecord::finder()->findByid($id);
		$smi->title				= $item->edttbTitle->Text;
		$smi->page				= $item->edtddlPage->SelectedValue;
		$smi->img				=  '';
		$smi->active			= TPropertyValue::ensureInteger($item->edtActive->Checked);
		$smi->role				= TPropertyValue::ensureInteger($item->edtRole->SelectedValue);
		$smi->target			= $item->edtddlTarget->SelectedValue;
		$smi->isbreak			= TPropertyValue::ensureInteger($item->edtcbSeparator->Checked);
		$smi->needlogin			= TPropertyValue::ensureInteger($item->edtcbNeedLogin->Checked);
		$smi->showafterlogin	= TPropertyValue::ensureInteger($item->edtcbShowAfterLogin->Checked);
		$smi->save();

		$this->dlSiteMenuItemsList->EditItemIndex=-1;
		$this->dlSiteMenuItemsList->DataSource	= $this->getDataRows($this->dlSiteMenuItemsList->PageSize * $this->dlSiteMenuItemsList->CurrentPageIndex,$this->dlSiteMenuItemsList->PageSize);
		$this->dlSiteMenuItemsList->dataBind();

		//Build our urlmap file
		$this->Application->BuildUrlMappingsForPath(true);
	}

	public function CancelContent($sender, $param)
	{
		//Build our urlmap file
		$this->Application->BuildUrlMappingsForPath(true);
		$this->gotoPage('Admin.SiteMenus');
	}

	public function getHaveParent()
	{
		return false;
	}

	public function Role2Txt($id)
	{
		switch($id)
		{
			case 0: return Prado::localize("All");
			default:
				$r = PortalRoleRecord::finder()->findByid($id);
				return $r->name;
		}
	}

	public function itemCommand($s,$p)
	{
		switch($p->CommandName)
		{
			case "movedown":	$this->MoveDown($p->CommandParameter); $this->gotoPage('Admin.SiteMenuEdit',array("id" => $this->Request['id'],"parent"=> $this->MenuParent)); break;
			case "moveup":		$this->MoveUp($p->CommandParameter); $this->gotoPage('Admin.SiteMenuEdit',array("id" => $this->Request['id'],"parent"=> $this->MenuParent)); break;
		}
	}

	public function editItem($sender,$param)
	{
		$item	= $param->Item;

		$this->dlSiteMenuItemsList->SelectedItemIndex	= -1;
		$this->dlSiteMenuItemsList->EditItemIndex		= $param->Item->ItemIndex;
		$this->dlSiteMenuItemsList->DataSource	= $this->getDataRows($this->dlSiteMenuItemsList->PageSize * $this->dlSiteMenuItemsList->CurrentPageIndex,$this->dlSiteMenuItemsList->PageSize);
		$this->dlSiteMenuItemsList->dataBind();

		//Build our urlmap file
		$this->Application->BuildUrlMappingsForPath(true);
	}

	public function getRoles()
	{
		return PortalRoleRecord::finder()->findAll();
	}

	public function getPages()
	{
		$a = PortalPageRecord::finder()->findAll('order by path');
		$pages = array();
		$pages[] = array('displayname' => Prado::localize('login'), 'fullpath' => 'User.Login','path' => 'User');
		$pages[] = array('displayname' => Prado::localize('Logout'), 'fullpath' => 'User.Logout','path' => 'User');
		$pages[] = array('displayname' => Prado::localize('New user'), 'fullpath' => 'User.NewUser','path' => 'User');
		$pages[] = array('displayname' => Prado::localize('Forgotten password'), 'fullpath' => 'User.ForgottenPassword','path' => 'User');
		$pages[] = array('displayname' => Prado::localize('View user'), 'fullpath' => 'User.ViewUser','path' => 'User');

		foreach($a as $b)
		{
			$pages[] = array('displayname' => $b->displayname, 'fullpath'	=> $b->fullpath, 'path' => $b->path);
		}
		return $pages;
	}

	public function ValidateUserRole($role)
	{
		if($role !== 0 && $role !== '0')
		{
			return $role;
		}
	}

	public function ValidatePageValue($page)
	{
		if($page !== 0 && $page !== '0' && $page !== '')
		{
			$pr = PortalPageRecord::finder()->findByfullpath($page);

			if($pr)
			{
				return $page;
			}
		}
	}

	public function cancelItem($sender,$param)
	{
		$this->dlSiteMenuItemsList->SelectedItemIndex=-1;
		$this->dlSiteMenuItemsList->EditItemIndex=-1;
		$this->dlSiteMenuItemsList->DataSource	= $this->getDataRows($this->dlSiteMenuItemsList->PageSize * $this->dlSiteMenuItemsList->CurrentPageIndex,$this->dlSiteMenuItemsList->PageSize);
		$this->dlSiteMenuItemsList->dataBind();

		//Build our urlmap file
		$this->Application->BuildUrlMappingsForPath(true);
	}

	public function deleteItem($sender,$param)
	{
		$item=$param->Item;
		$id = $this->dlSiteMenuItemsList->DataKeys[$item->ItemIndex];
		PortalSiteMenuItemRecord::finder()->deleteByid($id);

		//Build our urlmap file
		$this->Application->BuildUrlMappingsForPath(true);

		$this->gotoPage('Admin.SiteMenuEdit',array("id" => $this->Request['id']));
	}

    public function ShowParent($sender,$param)
    {
    	$mi = PortalSiteMenuItemRecord::finder()->findByid($this->MenuParent);
    	$p = $mi !== null ? $mi->parent : 0;
    	$m	= $mi !== null ? $mi->smid : $this->Request['id'];
		$this->gotoPage('Admin.SiteMenuEdit',array("id" => $this->Request['id'],"parent"=>$p));
	}

	public function MoveUp($id)
	{
		$row = PortalSiteMenuItemRecord::finder()->findByid($id);

		if($row)
		{
			$row->displayorder	-= 1.001;
			$row->save();
			$this->RenumDisplayOrder();
			$this->RenumDisplayOrder(1);
		}
	}

	public function MoveDown($id)
	{
		$row = PortalSiteMenuItemRecord::finder()->findByid($id);
		if($row)
		{
			$row->displayorder	+= 1.001;
			$row->save();
			$this->RenumDisplayOrder();
			$this->RenumDisplayOrder(1);
		}

		$this->dlSiteMenuItemsList->DataSource	= $this->getDataRows(0,$this->dlSiteMenuItemsList->PageSize * $this->dlSiteMenuItemsList->CurrentPageIndex);
		$this->dlSiteMenuItemsList->dataBind();
	}

	public function RenumDisplayOrder($p_startat = 999.000)
	{
		$newdisplayorder	= $p_startat;
		$sql				= "select * from tblsitemenuitem where smid= " . $this->SiteMenuRecord->id . " and parent=" . $this->MenuParent . " order by displayorder";
		$rows				= $this->DataAccess->createCommand($sql)->query();

		if($rows)
		{
			foreach($rows as $row)
			{
				$sql = "update tblsitemenuitem set displayorder=$newdisplayorder where id='" . $row["id"] . "'";
				$this->DataAccess->createCommand($sql)->execute();
				$newdisplayorder++;
			}
		}
	}

	public function HaveMenus($id,$pid)
	{
		return $this->DataAccess->createCommand("select count(id) from tblsitemenuitem where smid=$id and parent=$pid")->queryScalar() == 0 ? Prado::localize('No') : Prado::localize('Yes');
	}

	public function checkNewPageDisplayname($sender,$param)
	{
		if($this->tcbCreateNewPage->Checked == 0) // Only validate if we should create a new page
		{
			$param->IsValid = true;
		}
		else
		{
			if($this->PageLayout->SelectedValue == "0")
			{
				$param->IsValid = false;
			}
			else
			{
				$param->IsValid = true;
			}
		}
	}

	private function CreateNewPage($smi)
	{
		// Insert into DB
		$pRecord				= new PortalPageRecord();
		$pRecord->displayname	= $this->tbTitle->Text;
		$pRecord->created		= time();
		$pRecord->modified		= $pRecord->created;
		$pRecord->layoutname	= $this->PageLayout->getSelectedValue();
		$pRecord->active		= TPropertyValue::ensureInteger($this->Active->Checked);
		$pRecord->createdby		= $this->User->Id;

		if($this->PagePath->SelectedValue != "" && $this->PagePath->SelectedValue != "0")
		{
			$pRecord->path		= $this->PagePath->SelectedValue;
			$pRecord->name		= $this->getPageName($pRecord->path);
			$pRecord->fullpath	= $this->PagePath->SelectedValue . '.' . $pRecord->name;
			$newPath			= 'Application.Pages.' . $pRecord->path;
		}
		else
		{
			$pRecord->name		= $this->getPageName();
			$pRecord->fullpath	= $pRecord->name;
			$newPath			= 'Application.Pages';
		}

		$pRecord->save();
		$fullNewPath	= Prado::getPathOfNamespace($newPath) . "/";
		$npname			= $pRecord->name;
		$npphpname		= str_replace("\\","/", $fullNewPath . "/" . $npname . ".php");
		$nppagename		= str_replace("\\","/", $fullNewPath . "/" . $npname . ".page");

		$phpcontent 	= "<?php\r\n// Autogenerated file - DON'T modify!!!\r\nclass $npname extends PortalPage\r\n{\r\n";
		$phpcontent 	.= "}\r\n?>";
		file_put_contents($npphpname,$phpcontent);

		$pagecontent	= "<com:TContent Id=\"Main\" />";
		file_put_contents($nppagename,$pagecontent);

		$smi->page = $pRecord->fullpath;
		$smi->save();
		$this->gotoPage($pRecord->fullpath,array("PageMode" => 1));
	}

	public function getPageName($path = null)
	{
		$pagename	= 'Page' . PortalUtil::GenId("pages_seq");

		// Check if the file exists
		$npPath		= 'Application.Pages.' . ($path !== null ? $path : '');
		$npFileName	= PortalUtil::PathName(Prado::getPathOfNamespace($npPath)) . $pagename;

		if(file_exists($npFileName . '.php'))
		{
			return $this->getPageName($path);
		}

		$fullpath	= ($path !== null ? $path . '.' . $pagename : $pagename);

		// Check page name
		if($this->DbConnection->createCommand("select id from tblpages where fullpath='$fullpath'")->queryScalar())
		{
			return $this->getPageName($path);
		}

		return $pagename;
	}

	public function dlPageChanged($sender,$param)
	{
		$item = $sender->Items[$sender->SelectedIndex];
		$this->tbTitle->Text = $item->Text;
    }
}
?>